import type { ModelStuck } from '@/types'
import { upperFirst, toLower } from 'lodash-es'

// 生成api描述文件
export const getApiDescString = (options: ModelStuck, whiteKeyList: string[]) => {
  //  生成创建的描述文件
  const getApiDescCreateString = (options: ModelStuck, whiteKeyList: string[]) => {
    const newWhiteKeyList = whiteKeyList.concat(['onlyId', 'editor', 'creator', 'orgId'])
    const filterFields = options?.content.filter((item) => !newWhiteKeyList.includes(item.name))
    const fields = filterFields.map(
      (item, index) =>
        `	${upperFirst(item.name)} ${item.type} \`json:"${item.name}"\`   //${item.remark}`
    )
    const str = `type Create${options.modelName}Req {\n\n${fields.join('\n\n')}\n\n}\n\n`
    const strResp = `type Create${options.modelName}Resp {\n\n }\n\n`
    return str + strResp
  }

  // 生成删除的描述文件
  const getApiDescDeleteString = (options: ModelStuck) => {
    const str = `
    type Delete${options.modelName}Req {
      OnlyId string \`json:"onlyId"\` //主键id
    }
    type Delete${options.modelName}Resp {
    }
    `
    return str
  }

  // 生成修改的描述文件
  const getApiDescUpdateString = (options: ModelStuck, whiteKeyList: string[]) => {
    const newWhiteKeyList = whiteKeyList.concat(['editor', 'creator', 'orgId'])
    const filterFields = options?.content.filter((item) => !newWhiteKeyList.includes(item.name))
    const fields = filterFields.map(
      (item, index) =>
        `	${upperFirst(item.name)}  ${item.type} \`json:"${item.name}"\`   //${item.remark}`
    )
    const str = `type Update${options.modelName}Req {\n\n${fields.join('\n\n')}\n\n}\n\n`
    const strResp = `type Update${options.modelName}Resp {\n\n }\n\n`
    return str + strResp
  }
  // 生成查询的描述文件
  const getApiDescQueryString = (options: ModelStuck, whiteKeyList: string[]) => {
    const newWhiteKeyList = whiteKeyList.concat(['creator', 'editor'])
    const commonFields: ModelItem[] = [
      {
        name: 'pageIndex',
        type: 'int64',
        remark: '分页页码'
      },
      {
        name: 'pageSize',
        type: 'int64',
        remark: '分页每页数量'
      }
    ]
    const filterFields = options?.content
      .filter((item) => !newWhiteKeyList.includes(item.name))
      .concat(commonFields)
    // 单个数据的item
    const itemsFiles = options?.content.map(
      (item, index) =>
        `	${upperFirst(item.name)}   ${item.type} \`json:"${item.name}"\`   //${item.remark}`
    )
    // 请求结构的
    const reqFields = filterFields.map(
      (item, index) =>
        `	${upperFirst(item.name)}    ${item.type} \`json:"${item.name}"\`   //${item.remark}`
    )
    const itemStr = `
    type ${options.modelName}Item {
  ${itemsFiles.join('\n\n')}
  }
  `

    const queryReq = `
    type Get${options.modelName}ListReq {
 ${reqFields.join('\n\n')}
     }
    `

    const queryResp = `
    type Get${options.modelName}ListResp {
       List []${options.modelName}Item  \`json:"list"\`  // 数据列表
       Total int64          \`json:"total"\`// 数据总数
      }
    `
    return itemStr + queryReq + queryResp
  }

  // 获取请求配置
  const getServiceString = (options: ModelStuck) => {
    const apiSvc: string[] = []
    apiSvc.push(
      `
      @doc "创建${options.modelName}"
      @handler create${options.modelName}
      post /${toLower(options.modelName)}/create (Create${options.modelName}Req) returns (Create${options.modelName}Resp); //创建
      `
    )

    apiSvc.push(
      `
      @doc "更新${options.modelName}"
      @handler update${options.modelName}
      post /${toLower(options.modelName)}/update (Update${options.modelName}Req) returns (Update${options.modelName}Resp); //更新
      `
    )

    apiSvc.push(
      `
      @doc "删除${options.modelName}"
      @handler delete${options.modelName}
      post /${toLower(options.modelName)}/delete (Delete${options.modelName}Req) returns (Delete${options.modelName}Resp); //删除
      `
    )

    apiSvc.push(
      `
      @doc "查询${options.modelName}"
      @handler get${options.modelName}List
      post /${toLower(options.modelName)}/list (Get${options.modelName}ListReq) returns (Get${options.modelName}ListResp); //查询
      `
    )

    return `
    @server(
      prefix: /admin/${toLower(options.modelName)}/v1
      group: ${toLower(options.modelName)}
      timeout: 5s
      jwt: JwtAuth
    )
    service admin {\n\n ${apiSvc.join('\n\n')} \n\n}\n\n
    `
  }

  return (
    getApiDescCreateString(options, whiteKeyList) +
    getApiDescDeleteString(options) +
    getApiDescUpdateString(options, whiteKeyList) +
    getApiDescQueryString(options, whiteKeyList) +
    getServiceString(options)
  )
}

/**
 * getApiCreateString
 */
export const getApiCreateString = (options: ModelStuck) => {
  const createString = `
	var createReq ${toLower(options.modelName)}.Create${options.modelName}Req
	err = copier.Copy(&createReq, req)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrMsg("创建内容时，输入转换出错"), "创建内容时，输入转换出错%v ", err)
	}
	createReq.Creator = ctxdata.GetUidFromCtx(l.ctx)
	createReq.OrgId = ctxdata.GetOriIdFromCtx(l.ctx)
	_, err = l.svcCtx.${options.modelName}Rpc.Create${options.modelName}(l.ctx, &createReq)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrMsg("新增内容失败"), "新增内容失败,req: %+v , err : %v ", req, err)
	}
	return
  `
  return createString
}

/**
 * getApiDeleteString:删除的API代码
 */
export const getApiDeleteString = (options: ModelStuck) => {
  const deleteString = `
  _, err = l.svcCtx.${options.modelName}Rpc.Delete${options.modelName}(l.ctx, &${toLower(options.modelName)}.Delete${options.modelName}Req{
		OnlyId: req.OnlyId,
	})

	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrMsg("删除内容失败"), "删除内容失败req: %+v , err : %v ", req, err)
	}
  return
  `
  return deleteString
}

/**
 * getApiQueryString:查询的Api代码
 */
export const getApiQueryString = (options: ModelStuck, whiteKeyList: string[]) => {
  const queryString = `
  var resp types.Get${options.modelName}ListResp

	var pbData ${toLower(options.modelName)}.Get${options.modelName}ListReq
	copier.Copy(&pbData, req)
	pbData.OrgId = ctxdata.GetOriIdFromCtx(l.ctx)
	pbRes, err := l.svcCtx.${options.modelName}Rpc.Get${options.modelName}List(l.ctx, &pbData)
	var list []types.${options.modelName}Item
	tools.CopyList(&list, pbRes.List)
	resp.List = list
	resp.Total = pbRes.Total
	return &resp, err
  `
  return queryString
}

/**
 * getApiUpdateString:更新的代码
 */
export const getApiUpdateString = (options: ModelStuck) => {
  const updateString = `
  var pbReq  ${toLower(options.modelName)}.Update${options.modelName}Req

	curUserId := ctxdata.GetUidFromCtx(l.ctx)
	_ = copier.Copy(&pbReq, req)
	pbReq.Editor = curUserId
	_, err = l.svcCtx.${options.modelName}Rpc.Update${options.modelName}(l.ctx, &pbReq)
	return
  `
  return updateString
}
